#include "ir.h"

U8 Lianfa;

U32 key_code_32=0;
U8 data_valid;
U8 data_code;
U8 data_code_neg;

ISR(INT0_vect)
//U32 Get_ir_code(void)
{
	unsigned int i;
	unsigned int j;

	cli();
	//P05CR &= ~0X40;//disable interrupt source

	for(j = 0;j<3130;j++)//delay 9ms
	{
		if(get_GPIO_bit(GPIO_PD, 2))//if p0.5 turn to high level,return,prevent mis-trigger
		{
			//P05CR |= 0X40;//enable interrupt source
			return ;
		}
	}
	key_code_32 = 0;
	//double hit detect
	while(!get_GPIO_bit(GPIO_PD, 2));//wait for high level
	for(j = 0;j<1065;j++)//delay 3ms
	{
		if(!get_GPIO_bit(GPIO_PD, 2))//if p0.5 turn to low level,break
		{
			//P05CR |= 0X40;
			Lianfa = 1;	
			return;
		}
	}
	for(j = 0;j<710;j++)//delay 2ms
	{
		if(!get_GPIO_bit(GPIO_PD, 2))//if p0.5 turn to low level,break
		{
			break;
		}
	}
	//IR data acquire 
	for(i=0;i<32;i++)// get system codes and data codes,TOTAL 32BIT
	{
		while(!get_GPIO_bit(GPIO_PD, 2));//wait for high level
		for(j = 0;j<540;j++);//delay 0.9ms
		if(get_GPIO_bit(GPIO_PD, 2))
		{
			key_code_32 |= 1;
			while(get_GPIO_bit(GPIO_PD, 2));//wait for low level
		}
		if(i<31)
		{
			key_code_32 <<= 1;
		}
	}
	//quantify and verify the IR data
	data_code = (unsigned char)((key_code_32&0x0000FF00)>>8);//get data code
	data_code >>= 8;
	data_code_neg = (unsigned char)(key_code_32&0x000000FF);//get data anti-code
	if(data_code == (~data_code_neg))
	{
		data_valid = 1;
	}
	//P05CR |= 0X40; 
	sei();
}
